class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int fast = 0, left = fast + 1, end = left + 1, right = nums.size() - 1;
        vector<vector<int>> v;
        while (fast < right - 2)
        {
            while (fast > 0 && nums[fast] == nums[fast - 1])
            {
                fast++;
                continue;
            }
            left = fast + 1;
            while (left < right - 1)
            {
                while (left > fast + 1 && nums[left] == nums[left - 1])
                {
                    left++;
                    continue;
                }
                end = left + 1;
                right = nums.size() - 1;
                while (end < right)
                {
                    long long sum = (long long)nums[fast] + (long long)nums[left] + (long long)nums[end] + (long long)nums[right];
                    if (sum == target)
                    {
                        v.push_back({ nums[fast],nums[left],nums[end],nums[right] });
                        end++;
                        right--;
                        while (end < right && nums[end] == nums[end - 1]) end++;
                        while (end < right && nums[right] == nums[right + 1]) right--;
                    }
                    else if (sum > target)
                    {
                        right--;
                    }
                    else
                    {
                        end++;
                    }
                }
                left++;
            }
            fast++;
        }
        return v;
    }
};